package categories

import (
	"context"
	"database/sql"
	"errors"
	"github.com/go-kit/kit/log"
)

type CategoryRepository interface {
	GetAll(ctx context.Context) ([]*Category, error)
	Save(ctx context.Context, category Category) error
}

type defaultCategoryRepository struct {
	Conn   *sql.DB
	logger log.Logger
}

func NewCategoryRepository(conn *sql.DB, logger log.Logger) CategoryRepository {
	return &defaultCategoryRepository{
		Conn:   conn,
		logger: logger,
	}
}

type CategoryRow struct {
	Id              sql.NullString
	Name            sql.NullString
	ParentId        sql.NullString
	CreateTimestamp sql.NullInt64
}

func (cr *defaultCategoryRepository) GetAll(ctx context.Context) ([]*Category, error) {
	rows, err := cr.Conn.Query("SELECT id,name,parentId,createTimestamp from category;")
	if err != nil {
		_ = cr.logger.Log("get category error:", err)
		return nil, errors.New("请重试")
	}
	defer func() {
		if err := rows.Close(); err != nil {
			_ = cr.logger.Log("get categories close err:", err)
		}
	}()
	var cats []*CategoryRow
	for rows.Next() {
		var row CategoryRow
		if err := rows.Scan(&row.Id, &row.Name, &row.ParentId, &row.CreateTimestamp); err != nil {
			_ = cr.logger.Log("get categories error:", err)
			continue
		}
		cats = append(cats, &row)
	}
	result := make([]*Category, 0, len(cats))
	for _, row := range cats {
		cat := &Category{
			Id:              row.Id.String,
			Name:            row.Name.String,
			ParentId:        row.ParentId.String,
			CreateTimestamp: row.CreateTimestamp.Int64,
		}
		result = append(result, cat)
	}
	return result, nil
}

func (cr *defaultCategoryRepository) Save(ctx context.Context, category Category) error {
	return nil
}
